﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
using MvcContrib;
using Peresvet.Extensions;
using Peresvet.Resources;

namespace Peresvet.Controllers
{
	public class HomeController : Controller
	{
		#region Actions

		public ActionResult Index()
		{
			var data = AppContext.ServiceFactory.NewsService.GetNews();
			return View(data != null ? data.ConvertNewsDataItemsToMVCModel() : null);
		}

		public ActionResult News(int id)
		{
			var data = AppContext.ServiceFactory.NewsService.GetNewsById(id);
			if (data != null)
				return View(data.ConvertNewsDataItemToMVCModel());

			return this.RedirectToAction(a => a.Index());
		}

		public ActionResult History()
		{
			return View();
		}

		public ActionResult ContactUs()
		{
			return View();
		}

		public ActionResult Galleries()
		{
			var data = AppContext.ServiceFactory.GalleriesService.GetGalleries();
			return View(data != null ? data.ConvertGalleryDataItemsToMVCModel() : null);
		}

		public ActionResult Gallery(int id)
		{
			var data = AppContext.ServiceFactory.GalleriesService.GetGallery(id);
			if (data != null)
				return View(data.ConvertGalleryDataItemToMVCModel());

			return this.RedirectToAction(a => a.Galleries());
		}

		public ActionResult Video()
		{
			var model = new Dictionary<string, string>();
			FillVideosModel(model);
			return View(model);
		}

		public ActionResult Error()
		{
			return View();
		}

		#endregion

		#region Internal Implementation

		private void FillVideosModel(IDictionary<string, string> model)
		{
			if (model == null) return;

			var videoFolderPath = HttpContext.Server.MapPath(AppConfig.VideoFolderPath);
			if (videoFolderPath == null || !Directory.Exists(videoFolderPath)) return;
			var directoryInfo = new DirectoryInfo(videoFolderPath);

			var files = directoryInfo.GetFiles();
			foreach (var file in files)
			{
				model.Add(string.Concat(AppConfig.VideoFolderPath.Replace("~", ""), file.Name).Replace(@"\", @"/"),
					file.Name.Substring(0, file.Name.LastIndexOf(".", System.StringComparison.Ordinal)));
			}
		}

		#endregion
	}
}
